//
//  NSString+Extension.m
//  CoolTennisBall
//
//  Created by Coollang on 16/9/5.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "NSString+Extension.h"
#import "NSDate+FormateString.h"

@implementation NSString (Extension)


+ (NSString *)checkIfNullWithString:(id)obj
{
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    } else if ([obj isKindOfClass:[NSNumber class]]) {
        return [obj stringValue];
    }
    return @"";
}

+ (NSString *)appCurrentVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = infoDictionary[@"CFBundleShortVersionString"];
    return appCurVersion;
}

+ (NSString *)appCurrentName {
    NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
    if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
    return appName;
}


- (BOOL)checkIsEnglishAndNumberWithInCounts:(NSInteger)count
{
    NSString *predicateStr = [NSString stringWithFormat:@"^[a-zA-Z0-9]{%zd}$",count];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",predicateStr];
    return [predicate evaluateWithObject:self];
}

- (NSString *)trimmingSpecailSymbolWithOutUnderLine
{
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=\\|~＜＞$€^•'@#$%^&*()+'\""]; //(@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\)
    return [self stringByTrimmingCharactersInSet:set];
}

- (NSString *)trimmingSpecailSymbol
{
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
    return [self stringByTrimmingCharactersInSet:set];
}

- (NSString *)trimingAllNumber {
    
    // Intermediate
    NSMutableString *numberString = [[NSMutableString alloc] init];
    NSString *tempStr;
    NSScanner *scanner = [NSScanner scannerWithString:self];
    NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    while (![scanner isAtEnd]) {
        // Throw away characters before the first number.
        [scanner scanUpToCharactersFromSet:numbers intoString:NULL];
        
        // Collect numbers.
        [scanner scanCharactersFromSet:numbers intoString:&tempStr];
        [numberString appendString:[NSString checkIfNullWithString:tempStr]];
        tempStr = @"";
    }
    return numberString.copy;
    
}

/**
 *  分钟转小时
 *  @param trainTime 秒数
 *
 *  @return 不足一小时-返回类似：34:23，大于1小时-返回类似 01:34:23
 */
+ (NSString *)stringWithTrainTime:(int)trainTime {
    
    int hour = trainTime / 3600;
    int second = trainTime % 60;
    int minute = (trainTime - hour * 3600) / 60;
    
    if (hour > 0) {
        return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hour, minute, second];
    }else {
        return [NSString stringWithFormat:@"%02zd:%02zd", minute, second];
    }
}

/**
 *  分钟转小时
 *  @param timeInterval 分钟数
 *
 *  @return 返回类似 0.9  1 的时间,单位小时
 */
+ (NSString *)stringHourAndMinuteWith:(NSInteger)timeInterval {
    
    
    CGFloat times = timeInterval / 60.0;
    
    if (times >= 1) {
        return [NSString stringWithFormat:@"%.0f",roundf(times)];
    }else {
        return [NSString stringWithFormat:@"%.1f",times];
    }
}

/**
 * 字典转json
 
 * NSJSONWritingPrettyPrinted  是有换位符的。
 
 * 如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有 换位符的
 */
+ (NSString*)dictionaryToJson:(id)dic {
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

+ (id)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:0
                                               error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


/**
 *  计算文本大小
 *  @param maxSize     文本的最大尺寸
 *  @param font        文本字体大小
 */
- (CGSize)textSizeWithtextMaxSize:(CGSize)maxSize font:(UIFont *)font
{
    NSDictionary *attr = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}

/**
 *
 *  @param currentVersion 服务器的版本号 如：v0.0.6
 *  @param version        硬件本地版本号 如：v0.0.4
 */
+ (BOOL)checkIsLastestVersion:(NSString *)currentVersion lastestVersion:(NSString *)version {
    
    NSString *tempCVersion = [currentVersion stringByReplacingOccurrencesOfString:@"V" withString:@""];
    
    NSString *tempLVersion = [version stringByReplacingOccurrencesOfString:@"V" withString:@""];
    
    tempCVersion = [tempCVersion stringByReplacingOccurrencesOfString:@"v" withString:@""];
    tempCVersion = [tempCVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    tempLVersion = [tempLVersion stringByReplacingOccurrencesOfString:@"v" withString:@""];
    tempLVersion = [tempLVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSLog(@"%@%@", tempCVersion, tempLVersion);
    //    修改这个方法，可以控制升级蓝牙控件的条件
    //    if ([tempCVersion isEqualToString:tempLVersion]) {
    //        return YES;
    //    }
    
    if ([tempCVersion floatValue] > [tempLVersion floatValue]) {
        return NO;
    }
    
    return YES;
}

@end
